package org.m8.auth.handler;

import jakarta.annotation.Resource;
import lombok.extern.slf4j.Slf4j;
import org.m8.auth.controller.vo.AuthLoginRespVO;
import org.m8.auth.handler.social.SocialAuthLoginRespVO;
import org.m8.auth.model.OAuth2AccessTokenDO;
import org.m8.auth.model.OAuth2TokenService;
import org.m8.auth.model.SocialUserBindDO;
import org.m8.user.model.User;
import org.springframework.beans.factory.InitializingBean;

/**
 * 抽象登录
 *
 * @author yidanjun
 * @date 2024/9/7
 **/
@Slf4j
public abstract class AbstractAuthLoginHandler implements AuthLoginHandler, InitializingBean {

    @Resource
    private OAuth2TokenService oAuth2TokenService;


    protected abstract void init();

    @Override
    public void logout(String accessToken) {
        OAuth2AccessTokenDO oAuth2AccessTokenDO = oAuth2TokenService.removeAccessToken(accessToken);
        if (oAuth2AccessTokenDO == null){
            // accessToken无效或已登出
            return;
        }

        log.info("已登出");
    }

    @Override
    public <V extends AuthLoginRespVO> V refreshToken(String refreshToken) {
        OAuth2AccessTokenDO oAuth2AccessTokenDO = oAuth2TokenService.refreshAccessToken(refreshToken);

        AuthLoginRespVO authLoginRespVO = new AuthLoginRespVO();
        authLoginRespVO.setRefreshToken(oAuth2AccessTokenDO.getRefreshToken());
        authLoginRespVO.setAccessToken(oAuth2AccessTokenDO.getAccessToken());
        authLoginRespVO.setUserId(authLoginRespVO.getUserId());
        authLoginRespVO.setExpiresTime(oAuth2AccessTokenDO.getExpiresTime());
        return (V)authLoginRespVO;
    }

    protected SocialAuthLoginRespVO createTokenAfterLoginSuccess(User user, SocialUserBindDO socialUserBindDO){

        // 创建 访问令牌
        OAuth2AccessTokenDO accessToken = oAuth2TokenService.createAccessToken(user.getUsername());
        SocialAuthLoginRespVO socialAuthLoginRespVO = new SocialAuthLoginRespVO();
        socialAuthLoginRespVO.setUserId(user.getUsername());
        socialAuthLoginRespVO.setOpenid(socialUserBindDO.getOpenid());
        socialAuthLoginRespVO.setAccessToken(accessToken.getAccessToken());
        socialAuthLoginRespVO.setRefreshToken(accessToken.getRefreshToken());
        socialAuthLoginRespVO.setExpiresTime(accessToken.getExpiresTime());
        // 构建返回结果
        return socialAuthLoginRespVO;
    }

    protected AuthLoginRespVO createTokenAfterLoginSuccess(User user){
        // 创建 访问令牌
        OAuth2AccessTokenDO accessToken = oAuth2TokenService.createAccessToken(user.getUsername());
        AuthLoginRespVO authLoginRespVO = new AuthLoginRespVO();
        authLoginRespVO.setUserId(user.getUsername());
        authLoginRespVO.setAccessToken(accessToken.getAccessToken());
        authLoginRespVO.setRefreshToken(accessToken.getRefreshToken());
        authLoginRespVO.setExpiresTime(accessToken.getExpiresTime());
        // 构建返回结果
        return authLoginRespVO;
    }

    @Override
    public void afterPropertiesSet() {
        this.init();
    }
}
